import serial
import time
import cv2
import requests
import threading


while True:
    try:
        # 初始化串口

        try:
            ser = serial.Serial('/dev/ttyACM0', 115200,timeout=0.5)

            def read_serial(msg):
                ser.write(msg.encode())
                for i in range(10):
                    try:
                        data = ser.readall()
                        if data:
                            data = data.decode()
                            return data
                        return "下位机超时"
                    except:
                        return "下位机超时"
        except:
            def read_serial(msg):
                return "下位机错误"

        # 服务器URL
        video_server_url = 'http://192.168.1.100:5800/upload_video/1'
        data_server_url = 'http://192.168.1.100:5800/upload_data/1'

        # 打开摄像头
        cap = cv2.VideoCapture('http://192.168.1.100/stream')

        if not cap.isOpened():
            print("Error: Could not open camera.")
            exit()

        try:
            i = 0
            while True:
                i = i + 1
                # 读取一帧
                ret, frame = cap.read()
                if not ret:
                    print("Error: Could not read frame.")
                    break

                # 将帧编码为JPEG格式
                _, img_encoded = cv2.imencode('.jpg', frame)

                # 从串口读取数据
                serial_data = read_serial("\r\n")

                # 将视频帧发送到服务器
                video_response = requests.post(video_server_url, files={'video': ('frame.jpg', img_encoded.tobytes(), 'image/jpeg')})

                if video_response.status_code == 200:
                    print("Video frame sent successfully")
                else:
                    print("Failed to send video frame")
                if(i%3==0):
                    i = 0
                    # 将串口数据发送到服务器
                    serial_data_str = serial_data.decode('utf-8')
                    data_response = requests.post(data_server_url, data={'serial_data': serial_data_str})

                    if data_response.status_code == 200:
                        print("Serial data sent successfully")
                    else:
                        print("Failed to send serial data")

                # 延迟一段时间（例如，每秒发送一帧）
                time.sleep(0.01)

        except KeyboardInterrupt:
            print("Interrupted by user")
    except Exception as e:
        print(e)
